<?php 

function my_function_admin_bar(){
    return false;
}
add_filter( 'show_admin_bar' , 'my_function_admin_bar');

add_theme_support('post-thumbnails');

add_action('init', '__enable_page_excerpts');
function __enable_page_excerpts () {
    add_post_type_support('page', 'excerpt');
}

function __get_post_excerpt ( $post_id ) {
	global $post;
	$post_backup = $post;
	$post = get_post( $post_id );
	setup_postdata( $post );
	
	$output .= get_the_excerpt();
	
	$post = $post_backup;
	setup_postdata( $post );
	
	return $output;
}

function __is_full_content_body () {
	$full = false;
	if ( is_singular() ) {
		$full = true;
	}
	else if ( __is_list() ) {
		global $__mainpost;
		if ( $__mainpost ) { 
			$full = __get_custom($__mainpost->ID,'list-full-content','true');
			$full = ($full == 'true');
		}
	}
	return $full;
}

add_action('wp_ajax_email-register', '__email_register_callback');
add_action('wp_ajax_nopriv_email-register', '__email_register_callback');

function __email_register_callback () {

	$email = $_POST["email"]; 
	if ( trim($email) == "" ) {
		_e("Please, enter your email in the register field.");
		die();
	}
	if ( preg_match( '/^[^@\s-]+@[^@\s-]+\.[^@\.\s-]+$/', $email ) == 0 ) {
		_e("Please, the email you entered does not seem valid.");
		die();
	}
	
	$to = 'xxx@gmail.com';
	$subject = sprintf(__("[%s] Email Register: %s"), "XXX", $email);
	$message = 
		"Email: $email\n\n" . 
		"--\n" .
		sprintf(__("This message was sent from email register form of %s site (%s)."), "Mioterapia", "http://mioterapia.com" );
	$headers = "From: $email";
	
	if ( wp_mail( $to, $subject, $message, $headers ) ) {
		printf(__("Email <%s> regitered successfully. Thanks!"), $email);
	}
	else {
		printf(__("Fail to register email <%s>. Please, try again later."), $email);
	}

	die();
}

add_option('__comments_in_popup', true);
//update_option('__comments_in_popup', true);

add_action( 'after_setup_theme', '__theme_setup' );
function __theme_setup () {
	load_theme_textdomain( 'nucleo', TEMPLATEPATH . '/languages' );
	register_nav_menus( array(
		'top' => 'Menu Principal',
		'bottom' => 'Menu Rodap&eacute;',
		'lateral' => 'Menu Lateral',
		'highlights' => 'Menu Destaques',
	));
}

function __is_blog () {
	return ( !is_page() && !is_search() && !__is_list() );
}

function __is_list () {
	global $templates;
	return ( $templates['template-list'] );
}

function __get_body_class () {
	global $post;
	$classes[] = 'post-' . $post->post_name;
	$classes[] = __get_custom( $post->ID, 'class', 'default' );
	
	global $templates;
	foreach( $templates as $template => $ison ) {
		if ( $ison ) {
			$classes[] = $template;
		}
	}
	return join( ' ', get_body_class($classes) );
}

add_filter( 'nav_menu_css_class', '__nav_menu_css_class', 10, 2 );
function __nav_menu_css_class( $classes, $item ) {

	$class = __get_custom( $item->object_id, 'class' );
	if ( $class != '' ) {
		array_push( $classes, $class );
	}
	return $classes;
}

function __render_menu_categories ( $menuid, $menuclass ) {
	$nocatid = wpml_get_object_id( 1, 'category' );
	$args = array (
		'echo'       => 0, // false
		'title_li'   => '',
		'orderby'    => 'name',
		'hide_empty' => 1, // true	
		'exclude'    => $nocatid // exclui "Sem Categoria"
	);
	$cats = wp_list_categories( $args );
	$cats = str_replace( 'cat-item', 'menu-item', $cats );
	print "<ul class='".$menuclass." menu-categories'>\n";
	echo $cats;
	print "</ul>\n";
}

function __get_sitemap_itens () {
    $group_id = __get_group_id( 'menu-top' );
	$itens = __get_page_list( $group_id );
	
    $group_id = __get_group_id( 'menu-bottom' );
	$itens_bottom = __get_page_list( $group_id );
	
	array_push( $itens, $itens_bottom );
	
	return $itens;
}

function __get_page_list ( $page_id ) {
	$itens = __get_children_pages( $page_id );
	foreach ( $itens as $item ) {
		$subitens = __get_page_list( $item->ID );
		if ( count($subitens) > 0 ) {
			$subitens = array_merge( array($item), $subitens );
			$itens[$item->ID] = $subitens;
		}
	}
	return $itens;	
}

function __render_sitemap ( $item, $nivel = 0 ) {

	if ( !is_array($item) ) {
		$head = array( $item );
		$tail = array();
	}
	else {
		$head = array_slice( $item, 0, 1 );
		$tail = array_slice( $item, 1 );
	}

	$link = get_permalink( $head[0]->ID );
	$title = $head[0]->post_title;
	print "<li class='sitemap-nivel-$nivel'><a href='$link'>$title</a>";
	if ( count($tail) > 0 ) {
		print "\n<ul>\n";
		foreach ( $tail as $item ) {
			__render_sitemap ( $item, $nivel+1 );
		}
		print "</ul>\n";
	}
	print "</li>\n";
}

function __get_menu_item_class ( $item_id ) {
	global $post;
	if ( is_singular() ) {
		$p = $post;
	}
	$class = __get_custom( $item_id, 'class' );
	if ( __check_ancestor_page( $p, $item_id )) {
		$class .= ' current-menu-ancestor';
	}
	if ( $p->ID == $item_id ) {
		$class .= ' current-menu-item';
	}
//		if ( $subitens ) {
//			$class .= ' open-cascade';
//		}
	return $class;
}

function __get_menu_subitens ( $item_id, $depth ) {
	$subitens = null;
	if ( $depth > 1 ) {
		$cascade = __get_custom( $item_id, 'cascade', 'true' );
		if ( $cascade == 'true' ) {
			$subitens = __get_children_pages( $item_id );
		}
	}
	return $subitens;
}

function __post_languages( $sentence='%s', $sep=', ', $before='', $after='' ) {
	if ( function_exists(icl_get_languages) ) {
		$languages = icl_get_languages('skip_missing=1');
		if ( count($languages) > 1 ) {
			echo $before;
			foreach ( $languages as $l ) {
				if ( !$l['active'] ) {
					$langs[] = '<a href="'.$l['url'].'">'.$l['translated_name'].'</a>';
				}
			}
			echo sprintf( $sentence, join($sep, $langs) );
			echo $after;
		}
	}
}

function __get_custom ( $post_id, $key, $default='', $multlang=true ) {
	$val = get_post_meta( $post_id, $key, true );
	if ( !$val && $multlang ) {
		$orig_id = wpml_get_object_id( $post_id, 'page', false, 'pt-br' );
		if ( $orig_id != $post_id ) {
			$val = get_post_meta( $orig_id, $key, true );
		}
	}
	if ( !$val ) {
		$val = $default;
	}
	return $val;
}

function __get_bookmark ( $bookmark ) {
    $args = array(
		'post_status' => 'publish',
		'post_type'   => 'page',
		'meta_key'    => 'bookmark',
		'meta_value'  => $bookmark
	);
    $page = get_posts($args);
	return get_permalink($page[0]->ID);
}

/**
 * Verifica se uma página tem um determinado ancestral.
 * @param $page página a ser verificada.
 * @param $ancestor ancestral procurado.
 */
function __check_ancestor_page ( $page, $ancestor_id ) {
	if ( $page->ID == $ancestor_id ) {
		return true;
	}
	else {
		if ( $page->post_parent == 0 ) {
			return false;
		}
		else {
			$parent = get_post( $page->post_parent );
			return __check_ancestor_page ( $parent, $ancestor_id );
		}
	}
}

function __get_random_page ( $group_name ) {
	$pages = __get_group_pages( $group_name );
	$rand = array_rand( $pages );
	return $pages[$rand];
}

/**
 * Obtém páginas de um certo grupo.  Um grupo é definido como sendo um conjunto de páginas 
 * filhas de uma página privada que tenha um campo personalizado com chave 'group' - o valor 
 * desde campo é o nome do grupo.
 * @param group_nome nome do grupo.
 */
function __get_group_pages ( $group_name, $orderby = 'menu_order' ) {
    $group_id = __get_group_id( $group_name );
	return __get_children_pages( $group_id, $orderby );
}

function __check_group_page ( $page, $group_name ) {
	if ( __get_custom( $page->ID, 'group' ) == $group_name ) {
		return true;
	}
	else {
		if ( $page->post_parent == 0 ) {
			return false;
		}
		else {
			$parent = get_post( $page->post_parent );
			return __check_group_page( $parent, $group_name );
		}
	}
}

/**
 * Obtém as sub-páginas de um certa página.
 * @param parent_id id da página mãe.
 * @param orderby critério de ordenação da páginas.
 */
function __get_children_pages ( $parent_id, $orderby = 'menu_order' ) {
	$pars = array (
		'numberposts' => -1,
		'post_parent' => $parent_id,
		'post_type' => 'page',
		'orderby' => $orderby,
		'order' => 'asc' 
	);
	$pages = get_children( $pars );
//	Print_r ($pages);
    return $pages;
}

function __get_select_attachs ( $post_id, $selected, $args = null ) {
	extract( $args, EXTR_SKIP );
	$attachs = __get_attachs( $post_id, $mime_type, $orderby );
	if ( count(v) > 0 ) {
		$name = $name != '' ? "name='$name'" : "";
		$class = $class != '' ? "class='$class'" : "";
		$select = "<select $name $class width='100%'>\n";
		$select .= "<option value=''>&nbsp;</option>";
		foreach ( $attachs as $attach ) {
			$selopt = "";
			if ( $attach->ID == $selected ) {
				$selopt = "selected='selected'";
			}
			$select .= sprintf( "<option value='%s' %s>%s</option>\n", 
							$attach->ID, $selopt, $attach->post_name );
		} 
		$select .= "</select>";
	}
	return $select;
}

function __get_attachs ( $post_id, $mime_type = '', $orderby = 'menu_order' ) {
	$pars = array (
		'numberposts' => -1,
		'post_parent' => $post_id,
		'post_type' => 'attachment',
		'post_mime_type' => $mime_type,
		'orderby' => $orderby,
		'order' => 'asc' 
	);
	$pages = get_children( $pars );
//	__pre($pages);
    return $pages;
}

function __get_post_image ( $post_id ) {
	$head = __get_custom( $post_id, 'header' );
	if ( $head != '' ) {
		$pars = array (
			'numberposts' => 1,
			'post_parent' => $post_id,
			'post_type' => 'attachment'
		);
		$attachs = get_children( $pars );
		foreach( $attachs as $attach ) {
			if ( $attach->post_title == $head ) {
				return $attach;
			}
		}
		return false;
	}
}

function __get_audio_player ( $audio_url ) {
	$player = get_bloginfo('stylesheet_directory') . "/flash/player_mp3_maxi.swf";
	$config = get_bloginfo('stylesheet_directory') . "/flash/player_mp3_maxi.xml";
	
	$output = "<object type='application/x-shockwave-flash' data='$player' width='80px' height='12px'>\n";
	$output .= "<param name='movie' value='$player' />\n"; 
	$output .= "<param name='wmode' value='transparent'/>\n";
	$output .= "<param name='bgcolor' value='#480000' />\n"; 
	$output .= "<param name='FlashVars' value='mp3=$audio_url&amp;configxml=$config' />\n";
	$output .= "</object>\n";
	return $output;
}

function __get_post_audio ( $post_id ) {
	$audio = __get_attachs( $post_id, 'audio' );
//	__pre( $audio );
	return array_shift($audio);
}

function __admin_link( $text='admin', $before='(', $after=')', $title=null ) {
	if ( !$title ) {
		$title = __('Site admin','nucleo');
	}
	echo $before . '<a href="' . get_option('siteurl') . '/wp-admin" title="'.$title.'">'. $text . '</a>' . $after ;
}

function __login_link( $text='login', $before='(', $after=')', $title=null, 
							$redirect_url=null ) {
	if ( !$title ) {
		$title = __('Log in','nucleo');
	}
	if ( !$redirect_url ) {
		$redirect_url = esc_attr($_SERVER["REQUEST_URI"]);
	}
	echo $before . '<a href="' . wp_login_url($redirect_url) . '" title="'.$title.'">'. $text . '</a>' . $after ;
}

function __logout_link( $text='logout', $before='(', $after=')', $title=null, 
							$redirect_url=null ) {
	if ( !$title ) {
		$title = __('Log out','nucleo');
	}
	if ( !$redirect_url ) {
		$redirect_url = esc_attr($_SERVER["REQUEST_URI"]);
	}
	echo $before . '<a href="' . wp_logout_url($redirect_url) . '" title="'.$title.'">'. $text . '</a>' . $after ;
}

function __is_comments_in_popup () {
	return get_option('__comments_in_popup');
}

/**
 * Obtém o ID da página agrupadora de um grupo.  A página agrupadora é uma página privada que
 * tenha um campo personalizado com chave 'group' e o valor desde campo é o nome do grupo.
 * @param group_nome nome do grupo.
 */
function __get_group_id ( $group_name ) {
    $args = array(
		'post_status' => 'publish,private',
		'post_type'   => 'page',
		'meta_key'    => 'group',
		'meta_value'  => $group_name 
	);
    $pages = get_posts($args);
	return $pages[0]->ID;
} 

function __get_page ( $page_name ) {
    $args = array(
		'post_status' => 'publish,private',
		'post_type'   => 'page',
		'name'        => $page_name
	);
    $pages = get_posts($args);
	return $pages[0];
}

function __get_filesize( $attach_id ) {
	$size_units = array( 'bytes', 'kB', 'MB', 'GB' );
	$src = get_attached_file( $attach_id );
	$size = filesize( $src );
	$unit = 0;
	while ( $size > 1024 ) {
		$size = $size/1024;
		$unit++;
	}
	if ( $size < 10 ) {
		$size = round( $size, 2 );
	}
	else if ( $size < 100 ) {
		$size = round( $size, 1 );
	}
	else {
		$size = round( $size, 0 );
	}
	return $size.'&nbsp;'.$size_units[$unit];
}

add_filter( 'wp_die_handler', '__get_wp_die_handler' );
function __get_wp_die_handler() {
	return '__wp_die_handler';
}
function __wp_die_handler ( $message, $title = '', $args = array() ) {
	if ( !is_string( $message ) ) {
		_default_wp_die_handler( $message, $title, $args );
	}
	else {
		$location = $_POST['redirect_to'].'&err='.rawurlencode($message);
		wp_redirect($location);
		die();
	}
}

/**
 * Obtém array com as iniciais dos títulos de um array de posts.
 * @param posts array de posts
 * @param sep separador
 * @return array com as initiais dos títulos do array de posts, sem repetições.
 */
function __get_initials ( $posts ) {
	foreach( $posts as $post ) {
		$ini = __get_initial( $post->post_title );
		$inis[ $ini ] = $ini;
	}
	return $inis;
}

function __make_links ( $arr ) {
	foreach( $arr as $a ) {
		$links[ $a ] = '<a href="#' . $a . '">' . $a . '</a>';
	}
	return $links;
}

function __echo_array ( $arr, $sep = ', ', $start = '[ ', $end = ' ]' ) {
	$first = true;
	echo $start;
	foreach( $arr as $a ) {
		if ( !$first ) {
			echo $sep; 
		}
		echo $a;
		$first = false;
	}
	echo $end;
}

/**
 * Obtém a letra inicial de uma string.  A letra retornada será sempre maiúscula.
 * @param str string
 * @return a primeira letra da string, como maiúscula.
 */
function __get_initial ( $str ) {
	$str = htmlentities( $str, ENT_COMPAT, get_bloginfo('charset'), false );
	$initial = strtoupper( substr( $str, 0, 1 ) );
	if ( $initial == '&' ) {
		$initial = strtoupper( substr( $str, 1, 1 ) );
	}
	return $initial;
}

add_filter( 'post_gallery', '__gallery_shortcode', 10, 2 );
function __gallery_shortcode( $output, $attr ) {
	global $post;

	static $instance = 0;
	$instance++;

	// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
	if ( isset( $attr['orderby'] ) ) {
		$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
		if ( !$attr['orderby'] )
			unset( $attr['orderby'] );
	}
	extract(shortcode_atts(array(
		'id'         => $post->ID,
		'size'       => 'full-size',
		'orderby'    => 'menu_order ID',
		'order'      => 'ASC'
	), $attr));

	$id = intval($id);
	$attachments = get_children_images( $id, $order, $orderby );

	if ( empty($attachments) )
		return '';

	if ( is_feed() ) {
		$output = "\n";
		foreach ( $attachments as $att_id => $attachment )
			$output .= wp_get_attachment_link($att_id, $size, true) . "\n";
		return $output;
	}

	$selector = "gallery-{$instance}";

	$style = "gallery-simple-style";
//	$style = "gallery-caption-style";
//	$style = "gallery-viewer-style";
	$output = "
		<div id='$selector' class='gallery $style'>";
	
	foreach ( $attachments as $id => $attachment ) {
		$link = get_permalink( $id ); 
		$image = get_image( $attachment, $size );
		$caption = $attachment->post_excerpt;
		$output .= "
			<div class='gallery-item'>
				<div class='gallery-thumb'>
					$image
				</div>
				<div class='gallery-caption'>
					$caption
				</div>
			</div>";
	}

	$output .= "
			<br class='gallery-ending'/>
		</div>\n";

	return $output;
}

function __pre( $obj ) {
	echo "<pre>";
	print_r( $obj );
	echo "</pre>";
}

function get_children_images ( $id, $order = 'ASC', $orderby = 'menu_order ID' ) {
	return get_children( array(
		'post_parent' => $id, 
		'post_status' => 'inherit', 
		'post_type' => 'attachment', 
		'post_mime_type' => 'image', 
		'order' => $order, 
		'orderby' => $orderby) );
}

function get_image ( $attachment, $size ) {
	$image = wp_get_attachment_image_src( $attachment->ID, $size );
	$caption = "";
	if ( trim($attachment->post_excerpt) ) {
		$caption .= wptexturize($attachment->post_excerpt);
	}
	return "<img src='$image[0]' title='$caption' alt='$caption'/>";
}

// multilingual theme integration
include (TEMPLATEPATH . '/include/ext/wpml-integration.php');
?>